package entityUpdater

import (
	"errors"
	"fmt"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisService"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Number"
	"gitee.com/fierce_wolf/go-fox-edge-common/edgeEntity"
	"time"
)

type DeviceCommStatusUpdater struct {
}

func (e *DeviceCommStatusUpdater) updateStatusEntity(deviceId int64, status interface{}) (err error) {
	// 定义一个最终的异常拦截，用来防止可能的代码BUG
	defer func() {
		if r := recover(); r != nil {
			err = errors.New(fmt.Sprintf("异常信息：%v", r))
		}
	}()

	if status == nil {
		return nil
	}

	commStatus := status.(map[string]interface{})

	statusEntity := edgeEntity.Type.DeviceStatusEntity.Instance()
	statusEntity.GetBaseEntity().Id = deviceId

	commFailedTime := Number.MakeInt64(commStatus["commFailedTime"])
	commSuccessTime := Number.MakeInt64(commStatus["commSuccessTime"])

	now := time.Now().UnixMilli()

	exist, err := commRedisService.GetEntityByServiceKey(edgeEntity.Type.DeviceStatusEntity.Type(), statusEntity.MakeServiceKey())
	if err != nil {
		return
	}

	if exist == nil {
		commFailedCount := 0
		if commFailedTime > 0 {
			commFailedCount++
		}

		statusEntity.BaseEntity.CreateTime = now
		statusEntity.BaseEntity.UpdateTime = now

		// 插入对象
		statusEntity.CommFailedCount = commFailedCount
		statusEntity.CommFailedTime = commFailedTime
		statusEntity.CommSuccessTime = commSuccessTime

		// 插入对象
		commRedisService.InsertEntity(statusEntity)
		return nil
	} else {
		existEntity := exist.(*edgeEntity.DeviceStatusEntity)

		commFailedCount := existEntity.CommFailedCount
		if commFailedTime > 0 {
			commFailedCount++
		} else {
			commFailedCount = 0
		}

		statusEntity.BaseEntity.UpdateTime = now

		// 更新对象
		statusEntity.CommFailedCount = commFailedCount
		statusEntity.CommFailedTime = commFailedTime
		statusEntity.CommSuccessTime = commSuccessTime

		return commRedisService.UpdateEntity(statusEntity)
	}
}
